/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jeff.springWebTestNG.itext;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.jeff.springWebTestNG.util.StringOperUtil;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author winnie
 */
public class ITextPlayer {
    private static final Logger LOG = Logger.getLogger(ITextPlayer.class.getName());
    private static final String WORK_PATH = "/Users/winnie/Documents/ecq_related/docs/temp";
    private static final String OUTPUT_NAME = "sz-wor";
    
    boolean needPageNo = true;
    String pageHeader = "WOC-000001-2013";
    String pageFooter = "PDF Footer";
    String stamp = "ORIGINAL";
    
    public static void main(String[] args) {
        new ITextPlayer().playITextPdf();
    }
    
    public void playITextPdf() {
        byte[] pdfBytes = null;
        try {
//            InputStream xhtmlIn = new FileInputStream(new File(WORK_PATH + "/sz-woc.html"));
//            byte[] xhtml = new byte[xhtmlIn.available()];
            byte[] xhtml = archiveHtml();         
            
//            xhtmlIn.read(xhtml);
            InputStream cssIn = new FileInputStream(new File(WORK_PATH + "/doc.css"));
            

            
            Document doc = new Document(PageSize.A4, 60, 60, 50, 50);
            System.out.println(doc.getPageSize().getHeight());//842.0
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(doc, out);
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
            doc.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, doc,
                    new BufferedInputStream(new ByteArrayInputStream(xhtml)), 
                    cssIn);
            
            doc.close();
            
            System.out.println(doc.getPageSize().getHeight());//842.0
            
            System.out.println(doc.getPageNumber());
            writer.close();
            FileOutputStream fos = new FileOutputStream(WORK_PATH + "/" + OUTPUT_NAME + ".pdf");
            pdfBytes = out.toByteArray();
            
            
            
            
            if (needPageNo || !StringOperUtil.isEmpty(pageHeader) || !StringOperUtil.isEmpty(pageFooter)) {
	            ByteArrayOutputStream newOut = new ByteArrayOutputStream();
	            PdfReader reader = new PdfReader(pdfBytes);
	            PdfStamper stamper = new PdfStamper(reader, newOut);
	            int n = reader.getNumberOfPages();
	            for (int i = 1; i <= n; i++) {
	                if (!StringOperUtil.isEmpty(stamp) || !StringOperUtil.isEmpty(pageHeader)) {
	                    int yPos = !StringOperUtil.isEmpty(stamp) && !StringOperUtil.isEmpty(pageHeader) ? 830 : 820;
	                    getHeaderTable(i, n).writeSelectedRows(0, -1, 40, yPos, stamper.getOverContent(i));
	                }
	                if (needPageNo || !StringOperUtil.isEmpty(pageFooter)) {
	                    getFooterTable(i, n).writeSelectedRows(0, -1, 40, 30, stamper.getOverContent(i));
	                }
	            }
	            stamper.close();
	            pdfBytes = newOut.toByteArray();
	        }
            
            if (pdfBytes != null)
                fos.write(pdfBytes);
            fos.close();
//	        pdf = out.toByteArray();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
        
    }
    
    private PdfPTable getHeaderTable(int x, int y) {
        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(515);
        table.setLockedWidth(true);
        table.getDefaultCell().setFixedHeight(20);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        if (!StringOperUtil.isEmpty(stamp)) {
            table.addCell(new Phrase(stamp, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 11)));
        }
        if (!StringOperUtil.isEmpty(pageHeader)) {
            table.addCell(new Phrase(pageHeader, FontFactory.getFont(FontFactory.HELVETICA, 11)));
        }
        return table;
    }

    private PdfPTable getFooterTable(int x, int y) {
        PdfPTable table = new PdfPTable((needPageNo && !StringOperUtil.isEmpty(pageFooter)) ? 2 : 1);
        table.setTotalWidth(515);
        table.setLockedWidth(true);
        table.getDefaultCell().setFixedHeight(20);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        if (!StringOperUtil.isEmpty(pageFooter)) {
            table.addCell(new Phrase(pageFooter, FontFactory.getFont(FontFactory.HELVETICA, 8)));
        }
        if (needPageNo) {
            if (!StringOperUtil.isEmpty(pageFooter)) {
                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            } else {
                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            }
            table.addCell(new Phrase(String.format("Page %d of %d", x, y), FontFactory.getFont(FontFactory.HELVETICA, 8)));
        }
        return table;
    }

    private byte[] archiveHtml() {
        BufferedReader br = null;
        try {
            File f = new File(WORK_PATH + "/" + OUTPUT_NAME + ".html");
            br = new BufferedReader(new FileReader(f));
            StringBuilder sb = new StringBuilder();
            
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
//            System.out.println(xhtml.length);
//            String archivePath = WORK_PATH + "/page-break-html-arichive.html";
//            FileOutputStream fos = new FileOutputStream(archivePath);
//            fos.write(xhtml);
//            fos.close();
            
            return sb.toString().getBytes("UTF-8");
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
            return null;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    
}
